package com.pkx.cloud.fse7.dms.staff.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.pkx.cloud.fse7.dms.staff.entity.Staff;
import com.pkx.cloud.fse7.dms.staff.service.StaffService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author chenwg
 * @date 2020.11.11 13:09
 */
@RestController
@Slf4j
@RequestMapping("/dms/staffService")
@Api(tags = {"用户管理"})
public class StaffController {
    @Resource
    private StaffService staffService;
    @Resource
    private RestTemplate restTemplate;
    @Value(value = "${pkx.web-url}")
    private String webUrl;
    @Value(value = "${pkx.redirect-url}")
    private String redirectUrl;

    /**
     * 用户新增
     *
     * @return
     */
    @PostMapping("")
    @ApiOperation("用户新增")
    public String addStaff(@RequestBody Staff staff) {
        return staffService.addStaff(staff);
    }

    /**
     * 用户修改
     *
     * @return
     */
    @PutMapping("")
    @ApiOperation("用户修改")
    public String editStaff(@RequestBody Staff staff) {
        return staffService.editStaff(staff);
    }

    /**
     * 用户删除
     *
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation("用户删除")
    public String removeStaff(@PathVariable String id) {
        return staffService.removeStaff(id);
    }

    @RequestMapping(value = "redirect", method = RequestMethod.GET)
    public void test(HttpServletRequest request, HttpServletResponse response, @RequestParam(defaultValue = "/Home/TitleSubMenu/1004") String url) throws IOException, ServletException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, String> value = new LinkedMultiValueMap<>();
        value.add("username", "test");
        value.add("password", "123");
        HttpEntity<Map> requestEntity = new HttpEntity<Map>(value, httpHeaders);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(webUrl + "/Home/LoginCheck/", requestEntity, String.class);
        List<String> strings = stringResponseEntity.getHeaders().get("Set-Cookie");
        // 获取 ASP.NET_SessionId
        String session = strings.stream().filter(str -> str.contains("ASP.NET_SessionId"))
                .findAny()
                .orElse("")
                .split(";")[0]
                .replace("ASP.NET_SessionId=", "");
        Cookie sessionId = new Cookie("ASP.NET_SessionId", session);
        sessionId.setPath("/");
        response.addCookie(sessionId);
        log.info("cookie:{}", strings.toString());

        String body = stringResponseEntity.getBody();
        log.info("body:{}", body);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        if (jsonObject.containsKey("success") && jsonObject.getBool("success") == true) {
            Cookie username = new Cookie("username", jsonObject.getStr("username"));
            Cookie mD5Password = new Cookie("MD5Password", jsonObject.getStr("MD5Password"));
            username.setPath("/");
            mD5Password.setPath("/");
            response.addCookie(username);
            response.addCookie(mD5Password);
        } else {
            return;
        }
        response.sendRedirect(redirectUrl + url);
    }
}
